package com.wzy.shirostudy.exception;

import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @program: shiro-study
 * @description: 自定义异常类
 * 来源于:https://www.cnblogs.com/sxdcgaq8080/p/6744371.html
 * @author: 1
 * @create: 2020-04-16 13:53
 **/
@Component
public class MyExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        //如果是shiro无权操作，因为shiro 在操作auno等一部分不进行转发至无权限url
        if (ex instanceof UnauthorizedException) {
            //指定跳转到没有权限的页面
            try {
                httpServletResponse.sendRedirect("/permission/not");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (ex instanceof UnauthenticatedException) {
            //未经身份验证的异常
            try {
                httpServletResponse.sendRedirect("/user/no/login");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        ex.printStackTrace();
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
        return mv;
    }
}
